package com.hyperzsoft.budget;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyperzsoft.budget.DBProvider.BudgetTable;
import com.hyperzsoft.budget.DBProvider.ExpenseType;
import com.hyperzsoft.utils.ColorSelectBar;

public class TypeEdit extends ListActivity {
	static private String TAG = "ExpenseList";
	
	private ArrayList<ExpenseType> m_Types = null;
	private ProgressDialog m_ProgressDialog = null;
	private typeListAdapter m_adapter;
	private Runnable viewTypes;
	private DBProvider dbProvider;
	Thread m_ProgressThread;
	private int mType_of;
	public long mSelectedID = -1;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.types_list);
		
		dbProvider = new DBProvider(this);
		
		mType_of = dbProvider.EXPENSE_TYPES;
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			if (bundle.containsKey("type_of")) {
				mType_of = bundle.getInt("type_of");
			}
		}
		
		setupList();
		setupClickListeners();
	}
	
	public void setupClickListeners() {
		// Set Click Listener
		Button save =(Button)findViewById(R.id.Edit_TypeSave); 
		save.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				saveTypeItem();
				setResult(RESULT_OK);
			}
		});
	}
	
	private void saveTypeItem() {
		
		dbProvider.open();
		ExpenseType type = dbProvider.new ExpenseType();
		
		type.NAME = ((EditText) findViewById(R.id.Edit_TypeName)).getText().toString();
		type.COLOR = ((ColorSelectBar) findViewById(R.id.Edit_TypeColor)).getColor();
		type.TYPE_OF = mType_of;
		
		if (mSelectedID == -1) {
			type.insert();
			((RelativeLayout) findViewById(R.id.types_list)).invalidate();
		} else {
			type._ID = mSelectedID;
			type.update();
		}
		dbProvider.close();
		
		((EditText) findViewById(R.id.Edit_TypeName)).setText("");
		((ColorSelectBar) findViewById(R.id.Edit_TypeColor)).setColor();
		setupListAdapter(true);
	}
	
	private final Runnable returnRes = new Runnable() {
		@Override
		public void run() {
			if(m_Types != null && m_Types.size() > 0){
				m_adapter.notifyDataSetChanged();
				for(int i=0;i<m_Types.size();i++)
					m_adapter.add(m_Types.get(i));
			}
			if (m_ProgressDialog.isShowing()) m_ProgressDialog.dismiss();
			
			m_adapter.notifyDataSetChanged();
		}
	};
	
	private void setupList() {
		float px;
		int topPad, leftPad;
		
		RelativeLayout rl = (RelativeLayout)findViewById(R.id.types_list);
		View v = getLayoutInflater().inflate(R.layout.types_list_footer, null);
		ListView lv = getListView();
		
		// Convert the dps to pixels
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		
		px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, this.getResources().getInteger(R.integer.type_list_footer_height), metrics);
		topPad = (int) (metrics.heightPixels - px);
		px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, this.getResources().getInteger(R.integer.type_list_width), metrics);
		leftPad = (int) (metrics.widthPixels - px) / 2;
		
		v.setPadding(leftPad, topPad, 0, 0);
		rl.addView(v, rl.getChildCount());
		
		setupListAdapter(false);
		
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				m_adapter.setSelectedPosition(position);
				//TODO: Load the types values into the footer fields for edit
				// 	and enable the save/cancel buttons
			}
		});
	}
	
	private void setupListAdapter(boolean isReload) {
		
		m_Types = new ArrayList<ExpenseType>();
		this.m_adapter = new typeListAdapter(this, R.layout.types_list_item, m_Types);
		setListAdapter(this.m_adapter);
		
		viewTypes = new Runnable(){
			@Override
			public void run() {
				getTypesList();
			}
		};
		
		m_ProgressThread =  new Thread(null, viewTypes, "BudgetThread");
		m_ProgressThread.start();
		m_ProgressDialog = ProgressDialog.show(this,    
				"Please wait...", (isReload) ? "Reloading data ..." : "Retrieving data ...", true);
	}
	
	private void getTypesList(){
		ArrayList<Object> workingList;
		
		try{
			m_Types = new ArrayList<ExpenseType>();
			dbProvider.open();
			workingList = dbProvider.selectAll(BudgetTable.EXPENSE_TYPE, getApplicationContext().getString(R.string.expense_type_name) + " asc", "type_of = ?", new String[] {Integer.toString(mType_of)});
			dbProvider.close();
			
			for (Object obj : workingList){
				m_Types.add((ExpenseType)obj);
			}
			
			workingList = null;
			
			Thread.sleep(500);
			Log.i("ARRAY", ""+ m_Types.size());
		} catch (Exception e) {
			Log.e(TAG, e.getStackTrace().toString());
		}
		
		runOnUiThread(returnRes);
	}
	
	protected void onPause() {
		super.onPause();
		if (m_ProgressDialog != null){m_ProgressDialog.cancel();}
		
	}
	
	@Override
	public void onSaveInstanceState(Bundle instanceState) {
		super.onSaveInstanceState(instanceState);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.type_edit_menu, menu);
			return true;
		} catch (Exception e) {
			Log.e(TAG, e.getStackTrace().toString());
			return false;
		}
	}
    
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		try {
			// Handle item selection
			switch (item.getItemId()) {
			case R.id.type_add:
				
				return true;
			case R.id.type_del:
				
				return true;
			case R.id.type_back:
				finish();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		} catch (Exception e) {
			Log.e(TAG, e.toString());
			return false;
		}
	}
	
	public class typeListAdapter extends ArrayAdapter<ExpenseType> {
		private int selectedPos = -1; 
		private final ArrayList<ExpenseType> items;
		
		public typeListAdapter(Context context, int textViewResourceId, ArrayList<ExpenseType> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}
		
		public void setSelectedPosition(int pos){
			LinearLayout ll;
			
			selectedPos = pos;
			
			ExpenseType expenseTypes = items.get(selectedPos);
			ll = (LinearLayout)findViewById(R.id.EditGroup_TypeName);
			((EditText)ll.findViewById(R.id.Edit_TypeName)).setText(expenseTypes.NAME);
			ll = (LinearLayout)findViewById(R.id.EditGroup_TypeColor);
			((ColorSelectBar)ll.findViewById(R.id.Edit_TypeColor)).setColor(expenseTypes.COLOR);
			
			mSelectedID = expenseTypes._ID;
			
			// inform the view of this change
			notifyDataSetChanged();
		}
		
		public int getSelectedPosition(){
			return selectedPos;
		}
		
		public long getSelectedIndexId() {
			ExpenseType expenseTypes = items.get(selectedPos);
			
			return expenseTypes._ID;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.types_list_item, null);
			}
			
			LinearLayout ll = (LinearLayout)v.findViewById(R.id.type_list_item);
			//TODO: no validation on View or Linear layout objects
			if(selectedPos == position){
				v.setBackgroundColor(Color.parseColor(getApplicationContext().getString(R.color.list_item_royal_blue)));
				//list_item_corn_yellow
				((TextView)v.findViewById(R.id.type_name)).setTextColor(Color.parseColor(getApplicationContext().getString(R.color.list_item_corn_yellow)));
				ll.setBackgroundColor(Color.parseColor(getApplicationContext().getString(R.color.list_item_translucent_midnight_blue)));
			} else {
				v.setBackgroundColor(Color.parseColor(getApplicationContext().getString(R.color.list_item_translucent_black)));
				((TextView)v.findViewById(R.id.type_name)).setTextColor(Color.parseColor(getApplicationContext().getString(R.color.list_item_default_white)));
				ll.setBackgroundColor(Color.parseColor(getApplicationContext().getString(R.color.list_item_translucent_black)));
			}
			
			ExpenseType expenseTypes = items.get(position);
			
			if (expenseTypes != null) {
				TextView tv = (TextView) v.findViewById(R.id.type_name);
				TextView id = (TextView) v.findViewById(R.id.type_id);
				
 				if (tv != null) {
					tv.setText(expenseTypes.NAME);   
				}
 				
				if(id != null){
					id.setText(Long.toString(expenseTypes._ID));
				}
			}
			
			return v;
		}
	}
}